package com.runtime.hongyunuser.service.Impl;

import com.runtime.hongyunuser.bean.Products;
import com.runtime.hongyunuser.bean.Userfavorites;
import com.runtime.hongyunuser.mapper.UserFavoriteMapper;
import com.runtime.hongyunuser.service.ProductService;
import com.runtime.hongyunuser.service.UserFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserFavoriteServiceImpl implements UserFavoriteService {

    @Autowired
    private UserFavoriteMapper userFavoriteMapper;
    @Autowired
    private ProductService productService;

    @Override
    public Userfavorites addFavorites(Long userId, Long productId) {
        Userfavorites existingItem = userFavoriteMapper.findByUserIdAndProductId(userId, productId);

        if (existingItem != null) {
            return existingItem;
        } else {
            // 如果不存在，创建新购物车项
            Products product = productService.getProductById(productId.intValue());
            if (product == null) {
                throw new RuntimeException("商品不存在");
            }

            Userfavorites newItem = new Userfavorites();
            newItem.setUserId(userId);
            newItem.setProductId(productId);

            userFavoriteMapper.save(newItem);
            return newItem;
        }
    }

    @Override
    public boolean isCollected(Long userId, Long productId) {
        Integer count = userFavoriteMapper.countByUserAndProduct(userId, productId);
        return count != null && count > 0;
    }

    @Override
    public boolean toggleCollect(Long userId, Long productId) {
        if (isCollected(userId, productId)) {
            return userFavoriteMapper.deleteByUserAndProduct(userId, productId) > 0;
        } else {
            Userfavorites entity = new Userfavorites();
            entity.setUserId(userId);
            entity.setProductId(productId);
            return userFavoriteMapper.insert(entity) > 0;
        }
    }
}
